// pages/homePage/step/step.js
const app = getApp();
import F2 from '@antv/wx-f2';
let chart = null;
F2.Global.setTheme({
  appendPadding: 15
});

function initChart(canvas, width, height) { // 使用 F2 绘制图表
  const data = [{
    steps: 0,
    weekday: "周一"
  }]
  chart = new F2.Chart({
    el: canvas,
    width: width,
    height: height
  });

  chart.source(data, {
    steps: {
      // ticks: [0, 2000, 4000, 6000, 8000, 10000, 12000]
      tickCount: 6,
      min: 0
    }
  });
  chart.tooltip({
    showItemMarker: false,
    background: {
      radius: 2,
      fill: '#F8A941'
    },
    valueStyle: {
      fontSize: 10,
      color: "#FFFFFF"
    },
    onShow(ev) {
      const {
        items
      } = ev;
      items[0].name = null;
      items[0].value = items[0].value + "步";
    }
  });
  let barWidth = 30 * (wx.getSystemInfoSync().windowWidth / 375) / 2;

  chart.interval().position('weekday*steps').color('l(0) 0:#FBD591 1:#F8A941').style({
    radius: [5, 5, 0, 0]
  }).size(barWidth);
  chart.render();
  return chart;
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    deviceNum: "",
    weekDay: '',
    end: "",
    now: "",
    nowWeek: "",
    weekText: "",
    nowMonth: "",
    monthText: "",
    nowYear: "",
    yearText: "",
    curTab: "1",
    targets: [],
    stepNum: "5000",
    targetStep: "8000",
    targetStepNum: "",
    length: "10公里",
    avaStepNum_week: "6000",
    avaStepNum_month: "6000",
    avaStepNum_year: "6000",
    reachDays_week: "5",
    reachDays_month: "12",
    reachDays_year: "180",
    targetOp: [5000, 6000, 7000, 8000, 9000, 10000, 11000, 12000],
    opts_week: {
      onInit: initChart
    },
    opts_month: {
      onInit: initChart
    },
    opts_year: {
      onInit: initChart
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    let now = new Date(new Date().getTime() - 24 * 60 * 60 * 1000).format("yyyy/MM/dd");
    let nowMonth = new Date().format("yyyy/MM");
    let weekday = app.utils.formatWeekday(new Date(now).getDay());
    let startWDate = new Date(now).getTime() - 6 * 24 * 60 * 60 * 1000;
    startWDate = new Date(startWDate).format("yyyy/MM/dd");
    let weekText = startWDate + " - " + now;
    let startMDate = new Date(now).getTime() - 14 * 24 * 60 * 60 * 1000;
    startMDate = new Date(startMDate).format("yyyy/MM/dd");
    let monthText = startMDate + " - " + now;
    let startYDate = new Date(now).getTime() - 335 * 24 * 60 * 60 * 1000;
    startYDate = new Date(startYDate).format("yyyy/MM");
    let yearText = startYDate + " - " + nowMonth;

    that.setData({
      weekDay: weekday,
      now: now,
      nowWeek: now,
      weekText: now,
      nowMonth: now,
      nowYear: now,
      end: now,
      weekText: weekText,
      monthText: monthText,
      yearText: yearText,
      deviceNum: wx.getStorageSync("deviceNum")
    })

    that.getStepData(that.data.deviceNum, that.data.now, 1);
    that.getStepTarget();
  },
  circleCanves(option) {
    var cxt_arc = wx.createCanvasContext(option.id);
    var gr = cxt_arc.createLinearGradient(0, 100, 100);
    gr.addColorStop(0, option.colorStart);
    gr.addColorStop(1, option.colorEnd);
    cxt_arc.setLineWidth(option.ringWidth);
    cxt_arc.setStrokeStyle('#d2d2d2');
    cxt_arc.setLineCap('round')
    cxt_arc.beginPath(); //开始一个新的路径
    cxt_arc.arc(option.x, option.y, option.radius, Math.PI * option.trackStart, Math.PI * option.trackEnd, false);
    //设置原点(80,80)，半径为50的圆的路径到当前路径
    cxt_arc.stroke(); //对当前路径进行描边

    cxt_arc.setLineWidth(option.ringWidth);
    cxt_arc.strokeStyle = gr;
    cxt_arc.setLineCap('round')
    cxt_arc.beginPath(); //开始一个新的路径
    cxt_arc.arc(option.x, option.y, option.radius, Math.PI * option.position1, Math.PI * option.position2, false);
    cxt_arc.stroke(); //对当前路径进行描边

    cxt_arc.draw();
  },
  drawCir(id, rate, colorStart, colorEnd) {
    let width = wx.getSystemInfoSync().windowWidth;
    this.circleCanves({
      id: id,
      ringWidth: width / 375 * 5,
      radius: width / 375 * 25,
      position1: 0.5,
      position2: 2 * rate + 0.5,
      x: width / 375 * 30,
      y: width / 375 * 30,
      colorStart: colorStart,
      colorEnd: colorEnd,
      trackStart: 2,
      trackEnd: 0
    });
  },
  //精确计算每天步数目标
  clacTarget(date) {
    let targets = [...this.data.targets].reverse();
    let target;
    if (!targets.length) return 8000;

    let current = new Date(date + " 00:00:00").getTime();
    if (current < new Date(targets[0].workTime + " 00:00:00").getTime()) return targets[0].stepTarget;
    targets.forEach((item, index) => {
      if (index < targets.length - 1) {
        let time1 = new Date(item.workTime + " 00:00:00").getTime();
        let time2 = new Date(targets[index + 1].workTime + " 00:00:00").getTime();
        if (time1 <= current && current < time2) {
          return target = item.stepTarget;
        }
      }
    })
    if (!target) target = targets[targets.length - 1].stepTarget;

    return target;

  },
  bindDateChange(e) {

    let weekDay = app.utils.formatWeekday(new Date(e.detail.value).getDay())
    this.setData({
      now: e.detail.value.replace(/-/g, "/"),
      targetStep: this.clacTarget(e.detail.value.replace(/-/g, "/")),
      weekDay: weekDay
    })

    this.getStepData(this.data.deviceNum, e.detail.value, 1);
  },
  bindDateChangeWeek(e) {
    let startDate = new Date(e.detail.value).getTime() - 6 * 24 * 60 * 60 * 1000;
    startDate = new Date(startDate).format("yyyy/MM/dd");
    let weekText = startDate + " - " + e.detail.value.replace(/-/g, "/");

    this.setData({
      nowWeek: e.detail.value,
      weekText: weekText
    })
    this.getStepData(this.data.deviceNum, e.detail.value, 2);
  },
  bindDateChangeMonth(e) {
    let startDate = new Date(e.detail.value).getTime() - 14 * 24 * 60 * 60 * 1000;
    startDate = new Date(startDate).format("yyyy/MM/dd");
    let monthText = startDate + " - " + e.detail.value.replace(/-/g, "/");

    this.setData({
      nowMonth: e.detail.value,
      monthText: monthText
    })

    this.getStepData(this.data.deviceNum, e.detail.value, 3);
  },
  bindDateChangeYear(e) {
    let startDate = new Date(e.detail.value).getTime() - 335 * 24 * 60 * 60 * 1000;
    startDate = new Date(startDate).format("yyyy/MM");
    let yearText = startDate + " - " + new Date(e.detail.value).format("yyyy/MM");

    this.setData({
      nowYear: e.detail.value,
      yearText: yearText
    })

    this.getStepData(this.data.deviceNum, e.detail.value, 4);
  },
  // 点击tab切换
  swichNav: function(e) {
    if (this.data.curTab === e.currentTarget.dataset.current) return;
    this.setData({
      curTab: e.currentTarget.dataset.current
    })

    if (e.currentTarget.dataset.current == 2) {
      this.getStepData(this.data.deviceNum, this.data.nowWeek, 2);
    } else if (e.currentTarget.dataset.current == 3) {
      this.getStepData(this.data.deviceNum, this.data.nowMonth, 3);
    } else if (e.currentTarget.dataset.current == 4) {
      this.getStepData(this.data.deviceNum, this.data.nowYear, 4);
    }
  },
  // 滑动切换tab
  bindChange: function(e) {
    this.setData({
      curTab: e.detail.current
    })
  },
  editTarget(e) {
    let that = this;

    app.api.ajaxSubmit("/node/wx/home/editStepTarget", {
      studentId: wx.getStorageSync("student").studentId,
      targetStep: that.data.targetOp[e.detail.value],
      workTime: that.data.now
    }).then(response => {
      if (response.data.error == 10000) {
        that.setData({
          targetStep: that.data.targetOp[e.detail.value],
          targetStepNum: that.data.targetOp[e.detail.value]
        })
        that.getStepTarget();
        wx.showToast({
          title: '设置成功',
          icon: "none",
          duration: 2000
        })
      }
    }).catch(err => {});
  },
  //获取步数目标
  getStepTarget() {
    let that = this;
    app.api.ajaxSubmit("/node/wx/home/getStepTarget", {
      studentId: wx.getStorageSync("student").studentId
    }).then(response => {
      let data = response.data.data;
      if (response.data.error == 10000 && data.length) {
        that.setData({
          targets: data,
          targetStep: data[0].stepTarget
        })
      }
    }).catch(err => {})
  },
  stepDayHandle(data) {
    if (!data || !data.length) data = [{
      totalSteps: 0
    }];

    let steps = data[0];
    this.setData({
      stepNum: steps.totalSteps
    })

    let w = steps.totalSteps / this.data.targetStep * 1;
    w = w >= 1 ? 1 : w;

    let width = wx.getSystemInfoSync().windowWidth;
    let ringWidth = width / 375 * 10;
    let radius = width / 375 * 80;
    let x = ringWidth + radius;
    this.circleCanves({
      id: 'canvasArc',
      ringWidth: ringWidth,
      radius: radius,
      position1: 3 / 4,
      position2: 1.5 * w + 0.75,
      x: x,
      y: x,
      colorStart: "#FBD591",
      colorEnd: "#F8A941",
      trackStart: 3 / 4,
      trackEnd: 1 / 4
    });

    this.drawCir('canvasStepDay', w, "#FBD591", "#F8A941");

    //计算运动距离
    let height = wx.getStorageSync("height");
    if (!height) {
      this.setData({
        length: "请在“我的小孩”中完善身高信息"
      })
    } else {
      height = height / 100;
      let length = Math.round(height * steps.totalSteps * 0.45 / 1000) + "公里";
      this.setData({
        length: length
      })
    }
  },
  stepWeekHandle(data) {
    if (!data || !data.length) data = [{
      stepPeriodDate: new Date(this.data.nowWeek).getTime(),
      totalSteps: 0
    }];
    let newArray = [];

    for (let i = 0; i < data.length; i++) {
      let weekday = app.utils.formatWeekday(new Date(data[i].stepPeriodDate).getDay()).replace("星期", "周");

      newArray.push({
        weekday: weekday,
        stepPeriodDate: data[i].stepPeriodDate,
        steps: data[i].totalSteps
      })
    }
    let avaSteps, totalSteps = 0,
      reachDays_week = 0;
    newArray.forEach(item => {
      totalSteps += item.steps;
      let target = this.clacTarget(new Date(item.stepPeriodDate).format("yyyy/MM/dd"));
      if (item.steps >= target) reachDays_week++;
    })
    avaSteps = totalSteps / newArray.length;
    this.setData({
      avaStepNum_week: Math.round(avaSteps),
      reachDays_week: reachDays_week
    })

    let stepsWeekChartComponent = this.selectComponent('#column-week');
    stepsWeekChartComponent.chart.changeData(this.dataRepair(newArray, this.data.nowWeek, 7));

    let w = avaSteps / 8000;
    w = w >= 1 ? 1 : w;
    let r = reachDays_week / 7;

    this.drawCir('canvasStepWeek', w, "#91D5FF", "#40A9FF");
    this.drawCir('canvasReachWeek', r, "#FBD591", "#F8A941");
  },
  stepMonthHandle(data) {
    if (!data || !data.length) data = [{
      stepPeriodDate: new Date(this.data.nowMonth).getTime(),
      totalSteps: 0
    }];
    let newArray = [];

    for (let i = 0; i < data.length; i++) {
      let weekday = new Date(data[i].stepPeriodDate).format("MM/dd");

      newArray.push({
        weekday: weekday,
        stepPeriodDate: data[i].stepPeriodDate,
        steps: data[i].totalSteps
      })
    }
    let avaSteps, totalSteps = 0,
      reachDays_month = 0;
    newArray.forEach(item => {
      totalSteps += item.steps;
      let target = this.clacTarget(new Date(item.stepPeriodDate).format("yyyy/MM/dd"));
      if (item.steps >= target) reachDays_month++;
    })
    avaSteps = totalSteps / newArray.length;
    this.setData({
      avaStepNum_month: Math.round(avaSteps),
      reachDays_month: reachDays_month
    })

    let newArr = [];
    this.dataRepair(newArray, this.data.nowMonth, 15).forEach(item => {
      newArr.push({
        weekday: item.date,
        steps: item.steps
      })
    });
    let stepsMonthChartComponent = this.selectComponent('#column-month');
    stepsMonthChartComponent.chart.changeData(newArr);

    let w = avaSteps / 8000;
    w = w >= 1 ? 1 : w;
    let r = reachDays_month / 15;

    this.drawCir('canvasStepMonth', w, "#91D5FF", "#40A9FF");
    this.drawCir('canvasReachMonth', r, "#FBD591", "#F8A941");
  },
  stepYearHandle(data) {
    if (!data || !data.length) data = [{
      stepPeriodDate: new Date(this.data.nowYear).getTime(),
      totalSteps: 0
    }];
    let newArray = [];

    for (let i = 0; i < data.length; i++) {
      let weekday = new Date(data[i].stepPeriodDate).format("MM");

      newArray.push({
        weekday: weekday,
        stepPeriodDate: data[i].stepPeriodDate,
        steps: data[i].totalSteps
      })
    }
    let avaSteps, totalSteps = 0,
      reachDays_year = 0;
    newArray.forEach(item => {
      totalSteps += item.steps;
      let target = this.clacTarget(new Date(item.stepPeriodDate).format("yyyy/MM/dd"));
      if (item.steps >= target) reachDays_year++;
    })
    avaSteps = totalSteps / newArray.length;
    this.setData({
      avaStepNum_year: Math.round(avaSteps),
      reachDays_year: reachDays_year
    })

    let newArr = [];
    let dataYear = new Map([
      ["01", []],
      ["02", []],
      ["03", []],
      ["04", []],
      ["05", []],
      ["06", []],
      ["07", []],
      ["08", []],
      ["09", []],
      ["10", []],
      ["11", []],
      ["12", []]
    ])
    let startMonth;
    this.dataRepair(newArray, this.data.nowYear, 365).forEach((item, index) => {
      if (index == 0) startMonth = item.month;
      let monthData = dataYear.get(item.month);
      monthData.push(item.steps);
      dataYear.set(item.month, monthData);
    });
    let that = this;
    dataYear.forEach((value, key) => {
      let num = 0;
      let sum = that.sum(value);
      value.forEach(item => {
        if (item != 0) num++;
      })
      newArr.push({
        steps: num == 0 ? 0 : parseInt(sum / num),
        weekday: key
      })
    })

    //按照开始月份调整数组顺序
    let index = startMonth * 1 - 1;
    let arrBegin = newArr.slice(0, index);
    let arrEnd = newArr.slice(index);
    let dataList = arrEnd.concat(arrBegin);

    let stepsYearChartComponent = this.selectComponent('#column-year');
    stepsYearChartComponent.chart.changeData(dataList);

    let w = avaSteps / 8000;
    w = w >= 1 ? 1 : w;
    let r = reachDays_year / 15;

    this.drawCir('canvasStepYear', w, "#91D5FF", "#40A9FF");
    this.drawCir('canvasReachYear', r, "#FBD591", "#F8A941");
  },
  sum(array) {
    let sum = 0;
    array.forEach(item => {
      sum = sum + item;
    })
    return sum;
  },
  //修复空白数据
  dataRepair(data, end, days) {
    let newArr = [];
    let endTime = new Date(end + " 23:59:59").getTime();
    let startTime = endTime - days * 24 * 3600 * 1000 + 1000;
    if (days == 365) {
      let year = new Date(endTime).getFullYear() - 1;
      let month = new Date(endTime).getMonth() + 2;
      month = month > 12 ? 12 : month;
      let date = year + "/" + month + "/01";
      startTime = new Date(date).getTime();
    }

    data.forEach((item, i) => {
      item.stepPeriodDate = new Date(new Date(item.stepPeriodDate).format("yyyy/MM/dd 18:00")).getTime();
    })

    data.forEach((item, i) => {
      if (i != 0) {
        let d = (item.stepPeriodDate - data[i - 1].stepPeriodDate) / (24 * 60 * 60 * 1000);
        d = Math.floor(d);
        if (d >= 1) {
          for (let j = 0; j < d - 1; j++) {
            let weekday = app.utils.formatWeekday(new Date(data[i - 1].stepPeriodDate + (j + 1) * (24 * 60 * 60 * 1000)).getDay())
              .replace("星期", "周");
            let month = new Date(data[i - 1].stepPeriodDate + (j + 1) * (24 * 60 * 60 * 1000)).format("MM");
            let date = new Date(data[i - 1].stepPeriodDate + (j + 1) * (24 * 60 * 60 * 1000)).format("dd");
            newArr.push({
              steps: 0,
              weekday: weekday,
              month: month,
              date: date
            })
          }

          let month = new Date(item.stepPeriodDate).format("MM");
          let date = new Date(item.stepPeriodDate).format("dd");
          newArr.push({
            steps: item.steps,
            weekday: item.weekday,
            month: month,
            date: date
          })
        } else {
          let month = new Date(item.stepPeriodDate).format("MM");
          let date = new Date(item.stepPeriodDate).format("dd");
          newArr.push({
            steps: item.steps,
            weekday: item.weekday,
            month: month,
            date: date
          })
        }
      } else if (i == 0) {
        let d = (item.stepPeriodDate - startTime) / (24 * 60 * 60 * 1000);
        d = Math.floor(d);
        if (d >= 1) {
          for (let j = 0; j < d; j++) {
            let weekday = app.utils.formatWeekday(new Date(startTime + j * (24 * 60 * 60 * 1000)).getDay())
              .replace("星期", "周");
            let month = new Date(startTime + j * (24 * 60 * 60 * 1000)).format("MM");
            let date = new Date(startTime + j * (24 * 60 * 60 * 1000)).format("dd");
            newArr.push({
              steps: 0,
              weekday: weekday,
              month: month,
              date: date
            })
          }

          let month = new Date(item.stepPeriodDate).format("MM");
          let date = new Date(item.stepPeriodDate).format("dd");
          newArr.push({
            steps: item.steps,
            weekday: item.weekday,
            month: month,
            date: date
          })
        } else {
          let month = new Date(item.stepPeriodDate).format("MM");
          let date = new Date(item.stepPeriodDate).format("dd");
          newArr.push({
            steps: item.steps,
            weekday: item.weekday,
            month: month,
            date: date
          })
        }
      }
      //结尾不连续
      if (i == (data.length - 1)) {
        let d = (endTime - item.stepPeriodDate) / (24 * 60 * 60 * 1000);
        d = Math.floor(d);
        if (d > 1) {
          for (let j = 0; j < d; j++) {
            let weekday = app.utils.formatWeekday(new Date(item.stepPeriodDate + (j + 1) * (24 * 60 * 60 * 1000)).getDay())
              .replace("星期", "周");
            let month = new Date(item.stepPeriodDate + (j + 1) * (24 * 60 * 60 * 1000)).format("MM");
            let date = new Date(item.stepPeriodDate + (j + 1) * (24 * 60 * 60 * 1000)).format("dd");
            newArr.push({
              steps: 0,
              weekday: weekday,
              month: month,
              date: date
            })
          }
        }
      }

    })

    return newArr;
  },
  //根据手环设备号获取步数
  getStepData(deviceNum, date, type) {
    let that = this;
    app.api.ajaxSubmit("/node/wx/home/getStepData", {
      deviceNum: deviceNum,
      type: type,
      date: date
    }).then(response => {
      if (response.data.error == 10000) {
        if (type == 1) return that.stepDayHandle(response.data.data);
        if (type == 2) return that.stepWeekHandle(response.data.data);
        if (type == 3) return that.stepMonthHandle(response.data.data);
        if (type == 4) return that.stepYearHandle(response.data.data);
      }
    }).catch(err => {})
  }
})